using Godot;
using Godot.Collections;
using System;
using System.Threading.Tasks;

namespace TopDownGodot.Src.Game
{
    public partial class SpawnPoint : Node
    {
        private const string SERVER_CHARACTER_ID = "1";
        private const int SPAWN_OFFSET = 0;
        private Dictionary<string, bool> _addedCharacters = [];
        private Dictionary<int, PackedScene> _characterScenes = new Dictionary<int, PackedScene>()
        {
            { 1, GD.Load<PackedScene>("res://scene/character/character_1.tscn") },
            { 2, GD.Load<PackedScene>("res://scene/character/character_2.tscn") },
            { 3, GD.Load<PackedScene>("res://scene/character/character_3.tscn") }
        };

        public override void _Ready()
        {
            //PlayerCharacterChoices(Multiplayer.p)
        }

        private void CharacterRoleChoices(string id, int characterId)
        {
            if (_addedCharacters.ContainsKey(id))
                return;

            if (_characterScenes.TryGetValue(characterId, out PackedScene scene))
            {
                var character = scene.Instantiate<CharacterBody2D>();
                character.Name = id;
                var player_count = GetChildCount();
                GD.Print(player_count);
                var offset = new Vector2(SPAWN_OFFSET * player_count, 0);
                character.Position = offset;
                CallDeferred("add_child", character);
                _addedCharacters[id] = true;
            }
            else
            {
                GD.PrintErr("角色生成错误");
            }
        }

        private async Task PlayerCharacterChoices(int characterId)
        {
            string id = Multiplayer.GetUniqueId().ToString(); // 获取自己的 peer ID

            if (Multiplayer.IsServer())
            {
                await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
                CharacterRoleChoices(id, characterId);
            }
            else
            {
                await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
                RpcId(1, nameof(CharacterRoleChoices), id, characterId); // 调用服务端的 RPC
            }
        }
    }
}